<?php

namespace app\beautiful\controller\miniapp\member;

use app\beautiful\model\CouponModel;

use app\beautiful\model\LevelModel;

use app\beautiful\model\logs\MemberBalanceLogsModel;

use app\beautiful\model\logs\MemberIntegralLogsModel;

use app\beautiful\model\member\MemberBalanceModel;

use app\beautiful\model\member\MemberCouponModel;

use app\beautiful\model\member\MemberIntegralModel;

use app\beautiful\model\order\BuyOrderModel;

use app\beautiful\model\project\OnceCardModel;

use app\beautiful\model\setting\SettingBalanceModel;

use app\beautiful\model\setting\SettingIntegralModel;

use app\beautiful\model\PartnerModel;

use app\beautiful\model\StaffModel;

use app\BaseController;

use app\common\logic\TokenLogic;
use app\common\model\ShopDetailModel;


class Member extends BaseController{

    

    

     //下发 支付相关内容 积分的设置 

    public function getPaymentOrderRole(){

        $return = [

            'is_integral_deduction_balance' => 0,//是否允许积分抵扣金钱

            'integral_deduction_balance_limit_rate' => 0,//积分最大抵扣金钱的比率

            'integral_exchange_balance'     => 0,//积分抵扣余额的汇率

            'coupons' => [], //优惠券

        ];

        $SettingBalance = SettingBalanceModel::where([['shop_id','=', $this->request->shopId]])->find();

        if(null !== $SettingBalance){

          $return['integral_deduction_balance_limit_rate'] = $SettingBalance->integral_deduction_balance_limit_rate; //积分抵扣的比率 百分比

        }

        $integralSetting = SettingIntegralModel::where([['shop_id','=', $this->request->shopId]])->find();

        if($integralSetting !== null){ //如果是空 代表不使用积分抵扣余额

            $return['integral_exchange_balance'] = $integralSetting->integral_exchange_balance;//汇率      

        }

        $today = date('Y-m-d',time());

        $coupons = MemberCouponModel::where([

            ['shop_id','=', $this->request->shopId],

            ['member_id','=', $this->request->memberId],

            ['valid_bg_time','<=',$today],

            ['valid_end_time','>=',$today],

            ['status','=',0],

        ])->limit(0,50)->select()->toArray(); //最多下发50条

        $return['coupons'] = $coupons;

        return $this->success($return);

    }



    

    //获取用户是否还是员工 和 分销员等 包括后期的是否是教练等 获取用户是否在该门店白名单

    public function getMemberRole(){

        $member=$this->request->member;

        $shopStaff = StaffModel::where([

            ['shop_id','=',$this->request->shopId],

            ['mobile','=',$member->mobile],

            ['status','=',1],

            ['is_delete','=',0]

        ])->find();

        $is_staff = $shopStaff===null ? 0 : 1;

        

        $partner = PartnerModel::where([

            //['shop_id','=',$this->request->shopId],

            ['mobile','=',$member->mobile],

            ['status','=',1],

            ['is_delete','=',0]

        ])->find();

        $is_partner =  $partner === null ? 0 : 1;

        $partner_role = $partner === null ? 0 : $partner->role_id;


        return $this->success([

            'info' =>[

                'is_staff'      => $is_staff,

                'is_partner'    => $is_partner,

                'partner_role'  => $partner_role

            ],

        ]);

    }

    

    public function show()

    {

        $member=$this->request->member;

        $member->append(['hidden_mobile','birthday']);

        $balance = MemberBalanceModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member->member_id],

                ['valid_bg_time','<=',$this->request->time()]

            ])->sum('remain_balance') ?? 0;

        $frozen_balance=MemberBalanceModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member->member_id],

                ['valid_bg_time','>',$this->request->time()]

            ])->sum('remain_balance') ?? 0;;





        $integral = MemberIntegralModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member->member_id],

                ['expire_time','>',$this->request->time()]

            ])->sum('remain_integral') ?? 0;



        $coupon_count = MemberCouponModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member->member_id],

            ])->count() ?? 0;

        $shopDetail = ShopDetailModel::find($this->request->shopId);

        $is_valid_member = 0;//是否为有效用户（在门店有效期的白名单内）

        if($member->white_list_shop){
            $white_list_shop_arr = json_decode($member->white_list_shop,true);

            $shop_id_arr = array_column($white_list_shop_arr, 'shop_id');

            $key = array_search($this->request->shopId, $shop_id_arr);

            if($key!==false){
                if($white_list_shop_arr[$key]['in_white_list']>0 && time()>=strtotime($white_list_shop_arr[$key]['start_time']) && time()<=strtotime($white_list_shop_arr[$key]['end_time'])) {
                    $is_valid_member = 1;
                }
            }
        }

        $return=[

            'member_info'=>[

                'member_id' => $member->member_id,

                'money'=>$member->money,

                'nick_name'=>$member->nick_name,

                'birthday' => $member->birthday, 

                'sex'       => $member->sex,

                'face'=>$member->face,

                'level_id'=>$member->level_id,

                'level_name'=>$member->level ? $member->level->name : '普通会员',

                'balance'=>$balance,

                'frozen_balance'=>$frozen_balance,

                'total_balance' =>round(($balance *  100  + $frozen_balance * 100)/100,2),

                'integral'=>$integral,

                'coupon_count'=>$coupon_count,

                'hidden_mobile'=>$member->hidden_mobile,

                'white_list_open' =>(null === $shopDetail)?0:$shopDetail->white_list_open,

                'is_valid_member' =>$is_valid_member,

            ]


        ];

        return $this->success($return);

    }



    //获取用户的Qrcode

    public function getMemberQrcode(){

        $member = $this->request->member;

        $code=rand(111111,999999);

        $member->code=$code;

        $member->save();

        return $this->success([

            'member_id'=>$member->member_id,

            'code'=>$code

        ]);

    }



    public function saveMemberInfo()

    {

        $nick_name = $this->request->param('nick_name');

        $sex = $this->request->param('sex/d',0);

        $birthday = $this->request->param('birthday');

        $face = $this->request->param('face');

        if(empty($nick_name) || mb_strlen($nick_name) >32) return $this->error('请输入昵称且昵称长度不能多余32');

        if(!in_array($sex,[0,1,2])) return $this->error('请选择性别');

        if(empty($birthday)) return $this->error('请选择生日');

        if(false === strtotime($birthday." 00:00:00")) return $this->error('请选择正确的生日');

        $birthday_arr=explode('-',$birthday);

        if(count($birthday_arr) !=3) return $this->error('请选择正确的生日');

        $birthday_year=$birthday_arr[0]; $birthday_month=$birthday_arr[1]; $birthday_day=$birthday_arr[2];

//        if((mb_strlen($birthday_year) !=4) || (mb_strlen($birthday_month) !=2) (mb_strlen($birthday_day) !=2)) return $this->error('请选择正确的生日');



        $member=$this->request->member;

        $member->nick_name=$nick_name;

        $member->sex=$sex;

        $member->birthday_year=$birthday_year;

        $member->birthday_month=$birthday_month;

        $member->birthday_day=$birthday_day;

        if(!empty($face)){

            $member->face = $face;

        }

        $member->save();



        return $this->success("修改成功");

    }





    public function getMemberBalanceLogs()

    {

        



        $datas=MemberBalanceLogsModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$this->request->memberId],

        ])->field('type,info,balance,give_balance,add_time')

            ->order(['add_time'=>'desc'])

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->select()->append(['add_time_format'])

            ->toArray();

        $return['datas']=$datas;

        if($this->request->page == 1){

            $setting_balance = SettingBalanceModel::where([['shop_id','=',$this->request->shopId]])->find();

            if(null !== $setting_balance){

                $return['setting_balance']=[

                    'is_frozen_give_money'=>$setting_balance->is_frozen_give_money,

                    'frozen_days'=>$setting_balance->frozen_days,

                    'can_recharge'=>empty($setting_balance->taocan_detail) ? 0 : 1,

                ];

            }

        }

        return $this->success($return);

    }



    //获取充值套餐

    public function getBalancePackage(){

        $setting_balance = SettingBalanceModel::where([['shop_id','=',$this->request->shopId]])->find();



        if(null === $setting_balance) return $this->error('充值配置未设置，无法充值');

        if(empty($setting_balance->taocan_detail)) return $this->error('充值套餐未设置，无法充值');



        $datas=$setting_balance->taocan_detail;

        $coupon_ids='';

        $once_card_ids='';

        foreach ($datas as $val){

            if(!empty($val['coupon'])){

                $coupon_ids=$coupon_ids.','.implode(',',$val['coupon']);

            }

            if(!empty($val['once_card'])){

                $once_card_ids=$once_card_ids.','.implode(',',$val['once_card']);

            }



        }

        $coupon_ids=explode(',',$coupon_ids);

        $today = date('Y-m-d', $this->request->time());

        $coupons=CouponModel::where([

            ['coupon_id','in',$coupon_ids],

            ['shop_id','=',$this->request->shopId],

            ['valid_end_time','>=',$today],

        ])->field('coupon_id,name')->select()->toArray();



        $once_cards=OnceCardModel::where([

            ['once_card_id','in',$once_card_ids],

            ['shop_id','=',$this->request->shopId],

        ])->field('once_card_id,name')->select()->toArray();



        $coupon_id=array_column($coupons,'coupon_id');

        $once_card_id =array_column($once_cards,'once_card_id');



        foreach ($datas as $key=>$val){

            $coupon_name=[];

            if(!empty($val['coupon'])){

                foreach ($val['coupon'] as $k=>$v){

                    $index = array_search($v, $coupon_id);

                    $coupon_name[]=$coupons[$index]['name'];

                }

            }

            $datas[$key]['coupon_money']=implode('、',$coupon_name);



            $once_card_name=[];

            if(!empty($val['once_card'])){

                foreach ($val['once_card'] as $k=>$v){

                    $index = array_search($v, $once_card_id);

                    $once_card_name[]=$once_cards[$index]['name'];

                }

            }

            $datas[$key]['once_card_name']=implode('、',$once_card_name);

        }



        $level = LevelModel::where([

            ['is_delete','=',0],

            ['shop_id','=',$this->request->shopId]

        ])->order(['vip_level'=>'asc'])->field('*')->select()->toArray();

        array_unshift($level,[

            'level_id'=>0,

            'name'=>'普通会员',

            'vip_level'=>0,

            'need_recharge'=>0,

        ]);



        $vip_level=$this->request->member->level ? $this->request->member->level->vip_level : 0;





        return $this->success(['datas'=>$datas,'level'=>$level,'recharge'=>$this->request->member->recharge,'vip_level'=>$vip_level]);

    }



    //获取我的积分明细

    public function getMemberIntegralLogs()

    {



        $datas=MemberIntegralLogsModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$this->request->memberId],

        ])->field('type,info,integral,add_time')

            ->order(['add_time'=>'desc'])

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->select()->append(['add_time_format'])

            ->toArray();

        $return['datas']=$datas;



        return $this->success($return);

    }



    public function getMemberBuyLogs()

    {

        $datas=BuyOrderModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$this->request->memberId],

            ['is_paid','=',1]

        ])->field('balance,vip_balance,coupon_money,integral_balance,add_time')

            ->order(['add_time'=>'desc'])

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->select()->append(['add_time_format','price','discount_money'])

            ->toArray();

        $return['datas']=$datas;



        return $this->success($return);

    }

}

